<template>
    <div>
        <!-- 面包屑头部区域 -->
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
          <!-- 搜索与添加区域 -->
          <el-row :gutter="20">
            <el-col :span="7">
              <el-input placeholder="请输入内容" v-model="inputInfo" clearable @clear="getUserList">
                <el-button slot="append" icon="el-icon-search" @click="searchFn"></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="addDialogvisible = true">添加用户</el-button>
            </el-col>
          </el-row>
          <!-- 用户列表区域 -->
          <el-table :data="userlist" border stripe>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="编号" prop="ID"></el-table-column>
            <el-table-column label="姓名" prop="username"></el-table-column>
            <el-table-column label="年龄" prop="age"></el-table-column>
            <el-table-column label="角色" prop="position"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{row}">
                <!-- {{scope.row}} -->
                <!-- 修改按钮 -->
                <el-tooltip effect="dark" content="修改角色" placement="top" :enterable="false">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(row)"></el-button>
                </el-tooltip>
                <!-- 删除按钮 -->
                <el-tooltip effect="dark" content="删除角色" placement="top" :enterable="false">
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(row.ID)"></el-button>
                </el-tooltip>
                <!-- 分配角色按钮 -->
                <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                  <el-button type="warning" icon="el-icon-setting" size="mini" @click="remakeUser"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页区域 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1,2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :disabled="isBanPage">
          </el-pagination>
          <!-- 添加用户对话框 -->
          <el-dialog
            title="添加用户"
            :visible.sync="addDialogvisible"
            width="50%"
            @close="addDialogClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password"></el-input>
              </el-form-item>
              <el-form-item label="年龄" prop="age">
                <el-input v-model="addForm.age"></el-input>
              </el-form-item>
              <el-form-item label="权限" prop="position">
                <el-select v-model="addForm.position" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <span slot="footer">
              <el-button @click="addDialogvisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 修改用户的对话框 -->
          <el-dialog
            title="修改信息"
            :visible.sync="editDialogVisible"
            width="50%"
           @close="editDialogClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
              <el-form-item label="编号">
                <el-input v-model="editForm.ID" disabled></el-input>
              </el-form-item>
              <el-form-item label="用户名" prop="username">
                <el-input v-model="editForm.username"></el-input>
              </el-form-item>
              <el-form-item label="年龄" prop="age">
                <el-input v-model="editForm.age"></el-input>
              </el-form-item>
              <el-form-item label="权限">
                <el-input v-model="editForm.position" disabled></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer">
              <el-button @click="editDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
          </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { role } from '../../assets/const/data.js'
export default {
  data () {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        pagenum: 1,
        pagesize: 2
      },
      // 用户列表数据
      userlist: [],
      total: 0,
      // 搜索框双向绑定的数据
      inputInfo: '',
      // 是否禁用分页
      isBanPage: false,
      // 对话框是否显示
      addDialogvisible: false,
      // 添加用户的数据表单
      addForm: {
        username: '',
        password: '',
        age: '',
        position: ''
      },
      // 选择器选项
      options: role,
      // 添加用户表单验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { min: 1, max: 2, message: '长度在 1 到 2 个字符', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请选择权限', trigger: 'blur' }
        ]
      },
      // 修改用户对话框是否显示
      editDialogVisible: false,
      // 修改用户表单数据
      editForm: {
        ID: '',
        username: '',
        age: '',
        position: ''
      },
      // 修改用户表单验证规则
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { min: 1, max: 2, message: '长度在 1 到 2 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 调用接口调用函数
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('user', { params: this.queryInfo })
      // console.log(res)
      if (res.status !== 200) return this.$message.error('获取用户列表失败')
      this.userlist = res.data
      this.total = res.total
      this.isBanPage = false
    },
    // 监听pagesize改变的事件
    handleSizeChange (newsize) {
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newpage) {
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    async searchFn () {
      const { data: res } = await this.$http.get('user/anyuser', { params: { userinfo: this.inputInfo } })
      // console.log(res)
      if (res.status !== 200) return this.$message.error('搜索失败')
      this.userlist = res.data
      this.total = this.userlist.length
      this.isBanPage = true
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定添加用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 预校验通过，发起请求
        const { data: res } = await this.$http.post('user/add', this.addForm)
        if (res.status !== 200) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 隐藏添加用户对话框
        this.addDialogvisible = false
        // 重新获取用户列表
        this.getUserList()
      })
    },
    // 点击修改按钮
    showEditDialog (e) {
      this.editDialogVisible = true
      this.editForm.ID = e.ID
      this.editForm.username = e.username
      this.editForm.age = e.age
      this.editForm.position = e.position
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定，提交修改信息
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('user/' + this.editForm.ID, this.editForm)
        this.editDialogVisible = false
        if (res.status !== 200) return this.$message.error('修改用户失败')
        this.$message.success('修改成功')
        this.getUserList()
      })
    },
    // 根据ID删除对应用户信息
    removeUserById (e) {
      // 弹框询问是否删除数据
      this.$confirm('是否确认删除？此操作将对用户进行软删除，如需恢复请联系数据库管理员', '注意', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: result } = await this.$http.delete('user/' + e)
        // console.log(result)
        if (result.status !== 200) return this.$message.error('删除失败，请检查网络或后台接口')
        this.$message.success('删除成功')
        this.getUserList()
      }).catch(err => err)
      // 用async/await,promiseRes来接受await this.$confirm 如果用户确认删除,则promiseRes返回值为字符串confirm,取消就会报错(如果写了catch,打印便不会报错)
      // console.log(promiseRes)
    },
    // 点击分配角色按钮
    remakeUser () {
      this.$alert('该功能需要配合权限管理使用，由于权限管理并未完成，故不予展开后续操作', '提示')
    }
  }
}
</script>

<style lang="less" scoped>

</style>
